package top.kpromise.note.modules.user.api;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import top.kpromise.common.base.Result;
import top.kpromise.common.error.KException;
import top.kpromise.common.utils.StringUtils;
import top.kpromise.common.utils.ValidationUtils;
import top.kpromise.note.base.BaseApi;
import top.kpromise.note.modules.user.entity.LoginUser;
import top.kpromise.note.modules.user.entity.UserEntity;
import top.kpromise.note.modules.user.model.LoginResult;
import top.kpromise.note.modules.user.service.LoginService;

@RestController
@Api(tags = {"登录相关"})
public class Login extends BaseApi {

    private final LoginService loginService;

    public Login(LoginService loginService) {
        this.loginService = loginService;
    }

    @RequestMapping(value = "/oauth2/login", method = RequestMethod.POST)
    @ApiOperation(value = "用户名密码登录")
    @ApiImplicitParam(name = "loginUser", dataType = "LoginUser",
            paramType = "body", required = true)
    public Result<LoginResult> login(@RequestBody LoginUser loginUser) throws Exception {
        ValidationUtils.throwIfValidateFailed(loginUser);
        UserEntity userEntity = new UserEntity();
        userEntity.setUserName(loginUser.getUserName());
        userEntity.setPassword(loginUser.getPassword());
        return loginService.login(userEntity);
    }

    @RequestMapping(value = "/oauth2/refreshToken", method = RequestMethod.GET)
    @ApiOperation(value = "刷新Token")
    @ApiImplicitParam(name = "refreshToken", dataType = "string",
            paramType = "query", required = true)
    public Result<LoginResult> refreshToken(String refreshToken) throws Exception {
        if (StringUtils.isEmpty(refreshToken)) throw new KException("RefreshToken不能为空");
        return loginService.refreshToken(refreshToken);
    }

    @RequestMapping(value = "/api/user/logout", method = RequestMethod.GET)
    @ApiOperation(value = "退出登录")
    public Result<String> logout() {
        loginService.logout(userName());
        return Result.success("退出登录成功");
    }
}
